let wrap = document.getElementById("wrap"),
  count = 0;
function doSomething(e) {
  wrap.innerHTML = count++;
}
wrap.onmousemove = throttle(doSomething, 2000,{
  leading:false,
  trailing:true
});

// 节流-时间戳
// function throttle(fn, wait) {
//   let _self,args,
//     oldTimestamp = 0;
//   return function () {
//     let nowTimestamp = new Date().valueOf()
//       _self = this;
//       args = arguments;
//     if (nowTimestamp - oldTimestamp > wait) {
//       fn.apply(_self, args);
//       oldTimestamp = nowTimestamp;
//     }
//   };
// }
// 节流-定时器
// function throttle(fn, wait) {
//   let _self,args,timeOut;
//   return function () {
//       _self = this;
//       args = arguments;
//       if(!timeOut){
//         timeOut = setTimeout(function(){
//           timeOut = null
//           fn.apply(_self, args);
//         },wait)
//       }
//   };
// }

function throttle(fn, wait, options = {
  leading:true,
  trailing:true
}) {
  let _self,
    args,
    timeOut,
    oldTimestamp = 0;
  return function () {
    let nowTimestamp = new Date().valueOf();
    _self = this;
    args = arguments;
    if ((nowTimestamp - oldTimestamp > wait) && options.leading) {
      if (timeOut) {
        clearTimeout(timeOut);
        timeOut = null;
      }
      fn.apply(_self, args);
      oldTimestamp = nowTimestamp;
    } else if (!timeOut && options.trailing) {
      timeOut = setTimeout(function () {
        oldTimestamp = new Date().valueOf();
        timeOut = null;
        fn.apply(_self, args);
      }, wait);
    }
  };
}
